﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using MensUnoShop.Models;
using MensUnoShop.Filters;
using MensUnoShop.Models.ViewModels;
using SenerPro;
using System.IO;

namespace MensUnoShop.Controllers
{
    public class PayController : Controller
    {
        //
        // GET: /Pay/
        private List<Tag> _toptaglist;
        private Logger _log = new Logger(Config.logpath);

        public ActionResult Index()
        {
            _toptaglist = TagFactory.GetTopTagList();
            IndexViewModel iv = new IndexViewModel { TOPLIST = _toptaglist };

            return View(iv);
        }               

        [NoCacheFilter]
        public ActionResult CreditCardFeedBack()
        {
            PayFactory pf = new PayFactory();
            PayInfo pi = new PayInfo();
            PayInfoCreditcard pic = new PayInfoCreditcard();
            StringBuilder sb1 = new StringBuilder(3000);
            SenerPro.Logger log = new Logger(Config.logpath);

            string CheckSum = Request.Params["CheckSum"] ?? string.Empty;
            string Prc = Request.Params["PRC"] ?? string.Empty;
            string Src = Request.Params["SRC"] ?? string.Empty;
            string ApprovalCode = Request.Params["ApprovalCode"] ?? string.Empty;
            string BankResponseCode = Request.Params["BankResponseCode"] ?? string.Empty;
            string MerchantNumber = Request.Params["MerchantNumber"] ?? string.Empty;
            string Cashid = Request.Params["OrderNumber"] ?? string.Empty;
            string Amount = Request.Params["Amount"] ?? string.Empty;
            string BatchNumber = Request.Params["BatchNumber"] ?? string.Empty;
            string CardNumber = Request.Params["CardNumber"] ?? string.Empty;
            string IssueBank = Request.Params["IssueBank"] ?? string.Empty;
            string EngName = Request.Params["EngName"] ?? string.Empty;

            string Final_Result = string.Empty;
            string chkMD5 = string.Empty;
            string P_CheckSum = string.Empty;

            if (Cashid != string.Empty)
            {
                Order o = OrderFactory.GetTempOrder(Cashid);
                pi = pf.GetPayInfo(int.Parse(Cashid));
                pic = pf.GetPayInfoCreditcard(int.Parse(Cashid));

                chkMD5 = pf.GetMD5Hash(MerchantNumber + Cashid + Prc + Src + Config.Code1 + Amount);//驗證藍新回傳資料
                log.RecordExceptionFormat(Config.tradelog, "交易資訊1", "cashid:" + Cashid + "\tPrc:" + Prc + "\tSrc" + Src + "\tMD5:" + chkMD5);
                log.RecordExceptionFormat(Config.tradelog, "交易資訊2", "check: " + CheckSum);
                if (CheckSum == chkMD5 && Prc.Trim() == "0" && Src.Trim() == "0")
                {
                    //授權成功
                    Final_Result = "1";
                    pf.UptCoLog(int.Parse(Cashid), "1");

                    if (o != null)
                    {
                        o.SetStatus(Config.OrderStatusType.Payment);
                        log.RecordExceptionFormat(Config.tradelog, "信用卡付費成功", Cashid + ";" + o.TXID);
                    }
                    else
                    {
                        log.RecordExceptionFormat(Config.tradelog, "授權成功但訂單不存在", Cashid);
                    }
                }
                else
                {
                    //授權失敗
                    Final_Result = "0";
                    pf.UptCoLog(int.Parse(Cashid), "2");
                    if (o != null)
                    {
                        o.SetStatus(Config.OrderStatusType.Fail);
                        //有折扣的要復原
                        foreach (var d in o.DSKLIST)
                        {
                            d.DealFail(o.TXID);
                        }
                        //釋放庫存
                        o.FreeStock();
                        log.RecordExceptionFormat(Config.tradelog, "信用卡授權失敗", Cashid + ";" + o.TXID);
                    }
                    
                }
                P_CheckSum = pf.GetMD5Hash(MerchantNumber + Cashid + Final_Result + Prc + Config.Code1 + Src + Amount);//回傳給藍新
                
                pf.UptCreditcardData(int.Parse(Cashid), pic.PERIOD, pic.CHECKSUM1, chkMD5, P_CheckSum,
                    Prc, Src, ApprovalCode, BankResponseCode, BatchNumber, CardNumber, IssueBank, EngName);                
            }
            else
            {
                //無Cashid
                Final_Result = "0";
                log.RecordExceptionFormat(Config.tradelog, "信用卡無cashID", "");
            }

            sb1 = sb1.Append("final_result=[" + Final_Result + "]<br>");
            sb1 = sb1.Append("P_MerchantNumber=[" + MerchantNumber + "]<br>");
            sb1 = sb1.Append("P_OrderNumber=[" + Cashid + "]<br>");
            sb1 = sb1.Append("P_Amount=[" + Amount + "]<br>");
            sb1 = sb1.Append("P_CheckSum=[" + P_CheckSum + "]<br>");
            sb1 = sb1.Append("final_return_PRC=[" + Prc + "]<br>");
            sb1 = sb1.Append("final_return_SRC=[" + Src + "]<br>");
            sb1 = sb1.Append("final_return_ApproveCode=[" + ApprovalCode + "]<br>");
            sb1 = sb1.Append("final_return_BankRC=[" + BankResponseCode + "]<br>");
            sb1 = sb1.Append("final_return_BatchNumber=[" + BatchNumber + "]<br>");

            Response.Clear();
            Response.Write(sb1.ToString());

            return View();
        }

        public ActionResult CreditCardFinish()
        {
            return Redirect("/order/query");
        }

        public ActionResult OfflinePaid()
        {
            PayFactory pf = new PayFactory();
            PayInfo pi = new PayInfo();
            PayInfoCS pics = new PayInfoCS();
            SenerPro.Logger log = new Logger(Config.logpath);

            string MerchantNumber = Request.Params["merchantnumber"] ?? string.Empty;
            string Cashid = Request.Params["ordernumber"] ?? string.Empty;
            string SerialNumber = Request.Params["serialnumber"] ?? string.Empty;
            string WriteoffNumber = Request.Params["writeoffnumber"] ?? string.Empty;
            string TimePaid = Request.Params["timepaid"] ?? string.Empty;
            string PaymentType = Request.Params["paymenttype"] ?? string.Empty;
            string Amount = Request.Params["amount"] ?? string.Empty;
            string Tel = Request.Params["tel"] ?? string.Empty;
            string Hash = Request.Params["hash"] ?? string.Empty;

            string chkHash = string.Empty;

            if (Cashid != string.Empty)
            {
                pi = pf.GetPayInfo(int.Parse(Cashid));
                pics = pf.GetPayInfoCS(int.Parse(Cashid));
                
                //驗證藍新回傳資料
                chkHash = pf.GetMD5Hash("merchantnumber=" + MerchantNumber + "&ordernumber=" + Cashid + "&serialnumber=" + SerialNumber
                    + "&writeoffnumber=" + WriteoffNumber + "&timepaid=" + TimePaid + "&paymenttype=" + PaymentType + "&amount=" + Amount + "&tel=" + Tel + Config.Code2);
                //chkHash = pf.GetMD5Hash(MerchantNumber + Cashid + SerialNumber + WriteoffNumber + TimePaid + PaymentType + Amount + Tel + Config.Code2);

                if (Hash == chkHash && int.Parse(Amount) == pi.AMOUNT)
                {
                    //繳款成功                    
                    Order o = OrderFactory.GetTempOrder(Cashid);
                    pf.UptCoLog(int.Parse(Cashid), "1");
                    if (o != null)
                    {
                        o.SetStatus(Config.OrderStatusType.Payment);
                        log.RecordExceptionFormat(Config.tradelog, "離線付費成功", Cashid+";"+o.TXID);
                    }
                    else
                    {
                        log.RecordExceptionFormat(Config.tradelog, "離線付費成功但訂單不存在", Cashid);
                    }
                }
                else
                {
                    //繳款失敗
                    pf.UptCoLog(int.Parse(Cashid), "2");
                    log.RecordExceptionFormat(Config.tradelog, "離線付費失敗", Cashid + "\r\n" + string.Join(";", Request.Form) + "\r\n" + MerchantNumber + "; " + Hash + "; " + chkHash);
                }                
            }
            else
            {
                //無Cashid
                log.RecordExceptionFormat(Config.tradelog, "無cashID", "");
            }
                        
            
            return View();
        }

    }
}
